package top.kikt.book.core.handlers

import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.*

class Sdlchxwz : BaseBookHandler() {
    override val host: String
        get() = "www.sdlchxwz.net"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val name = document.metaContentWithProperty("og:novel:book_name")
        val author = document.metaContentWithProperty("og:novel:author")
        val coverUrl = document.metaContentWithProperty("og:image")
        return BookMetaEntity(name, url, url, author, coverUrl)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val list = document.select("#list > dl")[0]
        var ignore = true
        val result = ArrayList<ChapterMetaEntity>()
        for (element in list.children()) {
            if (element.tagName() == "dt") {
                if (element.text().trim().endsWith("正文")) {
                    ignore = false
                }
            }
            if (ignore) {
                continue
            }
            if (element.tagName() != "dd") {
                continue
            }
            val a = element.select("dd > a")
            val title = a.text()
            val href = a.attr("href")
            val url = menuUrl.resolve(href)
            val index = result.count()
            val entity = ChapterMetaEntity(title, index, url, element)
            result.add(entity)
        }

        return result
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val document = chapterMetaEntity.toDocument(charset) ?: return null

        val text = document.wholeText("#content")

        return ChapterEntity(
            chapterMetaEntity.name,
            chapterMetaEntity.index,
            text,
        )
    }
}